# coding:utf-8
import os
import operator
from itertools import chain

from enum import Enum, unique

SMS_QUEUE = 'sms'

WPH_SMS_QUEUE = 'wph_sms'

ALLIANCE_SMS_QUEUE = 'alliance_sms'

MULTI_SMS_QUEUE = 'multi_sms'

WPH_MULTI_SMS_QUEUE = 'wph_multi_sms_queue'

WECHAT_QUEUE = 'wechat'

WECHAT_USER_QUEUE = 'wechat_user_queue'

CAPTCHA_QUEUE = 'captcha_sms'

IM_QUEUE = 'im_sync'

IM_MESSAGE = 'im_message'

SYNC_USER_QUEUE = 'sync_user_zone'

ZONE_STAT_EXCHANGE = 'war_stat_exchange'

SEVEN_MOOR_AUDIO_UPLOAD_QUEUE = 'seven_moor_audio_upload_queue'

DEMAND_WINNER_QUEUE = 'demand_winner_queue'

IM_CLIENT_QUEUE = 'im_client_queue'

MARKETING_DEMAND_SMS_QUEUE = 'marketing_demand_sms_queue'

COMMON_API_QUEUE = 'common_api_queue'

ASSIGN_RED_PACKET_QUEUE = 'assign_red_packet_queue'

USE_SMS_BID_WIN_NOTIFY = 'use_sms_bid_win_notify'

PARTIC_CACHE_KEY = 'partic_info_{demand_id}_{demand_status}'
# partic_info的缓存key前缀, 用于清除缓存时用
PARTIC_CACHE_KEY_PREFIX = 'partic_info_{demand_id}_*'
PARTIC_CACHE_TIMEOUT = 3600 * 24 * 2  # 2天缓存

# 外呼是否使用虚拟号
OUTBOUND_USE_VIRTUAL_NUMBER = 'outbound_use_virtual_number'
# 繁忙坐席
BUSY_7MOOR_AGENTS = 'busy_7moor_agents'

# 项目中标人数
BID_USER_LIMIT = 'bid_user_limit'
MAINTAIN_USER_LIMIT = 'maintain_user_limit'

# 浇水虚拟工程商列表
WATERING_USER_IDS = 'watering_user_ids'

# 浇水指数(对期望成交价产生影响)
WATERING_INDEX = 'watering_index'

# 二次发布浇水系数
SECOND_WATERING_INDEX = 'second_watering_index'

# 多次发布浇水系数（3次及以上）
OTHER_WATERING_INDEX = 'other_watering_index'


# 发送验证码的通道key
Captcha_Sms_Channel_Key = 'captcha_sms_channel'

# 无理由退款次数增加的计数器
FREE_REASON_COUNTER_KEY = 'free_reason_counter_{user_id}'

# 企业每天报价人数缓存key
ENTERPRISE_OFFER_CNT_KEY = 'enterprise_offer_cnt_{id}_{date}'
# 过期时间： 1天
ENTERPRISE_OFFER_CNT_KEY_TIMEOUT = 60 * 60 * 24

# 梦网配置
SMS_CONFIG = {
    'CAPTCHA_USERID': 'JS5111',  # 专门用来发送验证码的，走的是梦网的生产通道，不可退订
    'CAPTCHA_PWD': '121563',
    'USERID': 'JS5187',          # 用来发送服务类,短信签名【万屏科技】，走得是梦网的服务通道，可退订
    'PWD': '125630',
    'MULTI_USERID': 'JS5112',     # 2018-7-16 由于原J92516通道被变更为页面通道, 因此改回使用JS5112
    'MULTIPWD': '858965',
    'WPH_USERID': 'JS5109',         # 签名【万屏汇】
    'WPH_PWD': '232265',
    'SMS_URL': 'http://61.145.229.28:7902/sms/v2/std/single_send',
    'MULTI_SMS_URL': 'http://61.145.229.28:7902/sms/v2/std/multi_send',

    'ALLIANCE_USERID': 'J93827',          # 签名【万屏汇联盟】
    'ALLIANCE_PWD': '956812',
    'ALLIANCE_SMS_URL': 'http://61.145.229.26:8086/sms/v2/std/single_send',
}


# 统一日期格式
DATE_FORMAT = '%Y-%m-%d'
TIME_FORMAT = '%H:%M'
DATETIME_FORMAT = '%Y-%m-%d %H:%M'

# 手机号or固话格式
PHONE_FORMAT = r'^(1(3|4|5|7|8)\d{9})|' \
               r'((0[0-9]{2,3}[-]{1})?([2-9][0-9]{6,7})+)$'

# 基本邮箱格式
EMAIL_FORMAT = r'(^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$)'


# 虚拟号就近原则对应表
TEL_X_AREA_MAP = {
    # 北京市 - 北京市
    '110000': ('110100', ),
    # 天津 - 北京
    '120000': ('110100', ),
    # 河北 - 北京、哈尔滨
    '130000': ('110100', '230100'),
    # 内蒙古 - 北京、哈尔滨、沈阳
    '150000': ('110100', '230100', '210100'),
    # 甘肃  - 北京
    '620000': ('110100', ),
    # 青海 - 北京
    '630000': ('110100', ),
    # 新疆 - 北京
    '650000': ('110100', ),
    # 宁夏 - 北京
    '640000': ('110100', ),
    # 黑龙江 - 哈尔滨
    '230000': ('230100', ),
    # 吉林 - 长春、哈尔滨
    '220000': ('220100', '230100'),
    # 辽宁 - 沈阳、哈尔滨
    '210000': ('210100', '230100'),
    # 上海 - 上海
    '310000': ('310100', ),
    # 江苏 - 上海、南京
    '320000': ('310100', '320100'),
    # 浙江 - 上海、杭州
    '330000': ('310100', '330100'),
    # 安徽 - 合肥、南京
    '340000': ('340100', '320100'),
    # 山东 - 济南
    '370000': ('370100', ),
    # 湖北 - 武汉
    '420000': ('420100', ),
    # 河南 - 郑州、武汉
    '410000': ('410100', '420100'),
    # 湖南 - 长沙、武汉
    '430000': ('430100', '420100'),
    # 山西 - 太原、郑州
    '140000': ('140100', '410100' ),
    # 陕西 - 郑州
    '610000': ('410100', ),
    # 广东 - 广州
    '440000': ('440100', '440300'),
    # 广西 - 南宁, 广州
    '450000': ('450100', '440100'),
    # 江西 - 南昌, 广州
    '360000': ('360100', '440100'),
    # 西藏 - 深圳
    '540000': ('440300', ),
    # 海南 - 深圳, 南宁
    '460000': ('440300', '450100'),
    # 香港 - 深圳
    '810000': ('440300',),
    # 澳门 - 深圳
    '820000': ('440300',),
    # 福建 - 深圳
    '350000': ('440300',),
    # 四川 - 深圳
    '510000': ('440300',),
    # 重庆 - 深圳
    '500000': ('440300',),
    # 贵州 - 昆明
    '520000': ('530100',),
    # 云南 - 昆明
    '530000': ('530100',),
}


APP_USER_ID_KEY = 'app_user_id_sets'


DEMAND_WEB_CALL = 'demand_web_call:{demand_id}:{published_count}'
OUTBOUND_KEY = 'outbound:{outbound_id}'

REGISTRATION_HASH = 'registration_ids_hash'
REGISTRATION_USER_HASH = 'registration_ids_user_hash'


# 数据状态常量 Enum 基类
class BaseStatusEnum(Enum):
    def __new__(cls, *args):
        obj = object.__new__(cls)
        obj._args_ = args
        obj._value_ = args[0]
        obj._display_ = args[1]
        return obj

    @property
    def args(self):
        return self._args_

    @property
    def display(self):
        return self._display_


class UnknownStatus(BaseStatusEnum):
    UNKNOWN = (None, '未知')


class StatusEnum(BaseStatusEnum):
    @classmethod
    def _missing_(cls, value):
        return UnknownStatus.UNKNOWN

    @classmethod
    def values(cls):
        return list(i.value for i in cls)

    @classmethod
    def to_dict(cls):
        return {i.value: i.display for i in cls}

    @classmethod
    def to_options(cls):
        return list((i.value, i.display) for i in cls)


class BidQueueStatus(object):
    """
    create by ld_wu 2018-01-27
    中标队列状态
    """
    WAITING = 1
    CALLED = 2
    RECHARGE = 3
    TIME_OUT = 4
    SPARE = 5
    TRAIN = 6

    mapping = {
        WAITING: '待呼叫',
        CALLED: '已呼叫',
        RECHARGE: '待充值',
        TIME_OUT: '超时未充值',
        SPARE: '排队中',
        TRAIN: '赠单'
    }


class BidNotifyType(object):
    # 竞拍成功
    WIN = 1
    # 竞拍成功待充值
    RECHARGE = 2


# 个人赠送次数
USER_TRAINING_COUNT = 'user_training_count:{}'

SEVEN_MOOR_NUMBERS = ['02161514624', '02161514640', '02161514693']

# 万屏员工号码列表, 统计时过滤
MEMBERS_PHONE = (
    '13699899775', '18817877341', '15801577693', '18910632128',
    '18588290314', '18381665312', '18680308092', '13825187899',
    '13421376954', '13430607063', '15603053210', '13424710263',
    '18038064601', '17682342507', '18718925917', '18516234676',
    '15889797200', '13684988236', '13017671158', '18221772171',
    '18682115996', '15166841990', '15674601234', '18229460730',
    '18826416361', '13296874281'
)

QINIU_APP_ID = os.environ.get('qiniu_app_id', 'pnRo5EGCRPE1f70cUD79Osa9TXgSAFBfApgPgAEW')
QINIU_SECRET_KEY = os.environ.get('qiniu_secret_key', '2ADUDqb8lq6QZwIQ031F50YlWXcUk-wyOJhmgebw')
QINIU_BUCKET_NAME = os.environ.get('qiniu_bucket_name', 'test')
QINIU_DOMAIN = os.environ.get('qiniu_domain', 'http://p94hl8abs.bkt.clouddn.com')


# 订单中标人数
BID_USER_COUNT = 3

# 订单通知数量
DEMAND_NOTIFY_LIMIT = 3

# 台湾area_id
TAIWAN_CODE = 710100


@unique
class VoucherStatus(StatusEnum):
    """
    create by ld_wu 2018-07-04
    代金券状态
    """
    AVAILABLE = (1, '未使用')
    USED = (2, '已使用')
    EXPIRED = (3, '已过期')


@unique
class GiveVoucherReason(StatusEnum):
    """
    created by lina at 2018/07/06
    赠送代金券理由
    """
    REFUND_OVERTIME_COMPENSATION = (1, '退款超时未申请补偿', 'overtime_compensation')      # 原退款超时补偿
    SLEEPY_WAKE_UP = (2, '沉睡唤醒', 'wake_up')
    RECALL = (3, '取关召回', 'recall')
    MAINTAIN = (4, '客情维护', 'maintain')
    SYSTEM_GIFT = (5, '新用户注册', 'sys_gift')      # 原系统赠送
    SYSTEM_INIT = (6, '系统初始化', 'sys_init')
    ACTIVATION = (7, '用户促活', 'activation')
    ACTIVITY = (8, '活动赠送', 'activity')
    REFUND_FEEDBACK_COMPENSATION = (9, '退款申述补偿', 'feedback_compensation')
    MARKETING = (10, '市场拉新', 'marketing')

    def stat_user_key(self, voucher_type):
        """
        create by ld_wu 2018-07-18
        人数统计的stat_type
        :return:
        """
        return '{}_{}_user_cnt'.format(voucher_type.display, self.args[-1])

    def stat_key(self, voucher_type):
        """
        create by ld_wu 2018-07-18
        张数统计的stat_type
        :return:
        """
        return '{}_{}_cnt'.format(voucher_type.display, self.args[-1])


class VoucherStatType(StatusEnum):
    """
    create by ld_wu 2018-07-18
    """

    GRANT = (1, 'grant', '发放总览')
    USED = (2, 'used', '消耗总览')
    INVENTORY = (3, 'inventory', '库存总览')
    EXPIRED = (4, 'expired', '失效总览')

    @property
    def table_ths(self):
        reason_keys = [
            (each.display, each.stat_key(self), each.stat_user_key(self))
            for each in GiveVoucherReason
        ]
        return list(
            chain(reason_keys, [('总计', self.stat_key, self.stat_user_key)])
        )

    @property
    def stat_user_key(self):
        return '{}_user_cnt'.format(self.display)

    @property
    def stat_key(self):
        return '{}_cnt'.format(self.display)

    @property
    def title(self):
        return self.args[-1]


@unique
class RedPacketStatus(StatusEnum):
    """
    add by zhouhl 2018-07-25
    汇币红包状态
    """
    NORMAL = (1, '正常')
    EXPIRED = (2, '过期')
    OVER = (3, '发放完毕')


RECEIVE_RED_PACKET_HISTORY = 'red_packet_history_{red_packet_id}'


class ColorRule(StatusEnum):
    """
    created by chenhj at 2018/8/17

    """
    FULL_COLOR = (1, '全彩')
    NOT_FULL_COLOR = (2, '非全彩')


class SpanRule(StatusEnum):
    """
    created by chenhj at 2018/8/17

    """
    SMALL = (1, '小间距(<P3)')
    LARGE = (2, '大间距(≥P3)')


class SizeOperator(StatusEnum):
    """
    created by chenhj at 2018/8/17

    """
    LE = (1, '≤', operator.le)
    GE = (2, '≥', operator.ge)

    @property
    def op(self):
        return self.args[2]


class RedeemStatus(StatusEnum):
    """
    created by chenhj at 2018/9/25

    """
    ACTIVE = (1, '未兑换')
    USED = (2, '已兑换')
    INACTIVE = (-1, '失效')


class RedeemType(StatusEnum):
    """
    created by chenhj at 2018/9/25

    """
    MARKETING = (10, '市场拉新')


class RedeemGiftType(StatusEnum):
    """
    created by chenhj at 2018/9/25

    """
    VOUCHER = (1, '代金券')
